<template>
  <span v-if="flag" style="color: red">(剩余{{ model.m }}:{{ model.s }})</span>
  <span v-else style="color: red">(支付超时)</span>
</template>

<script>
// import { clearTimeout } from 'timers';
// import { setTimeout } from 'timers/promises';

export default {
  name: 'TimingModule',
  props: ['endTime'],
  data() {
    return {
      model: {
        m: '00', // 分钟
        s: '00' // 秒
      },
      timedown: null,
      flag: true
    }
  },
  watch: {
    endTime: {
      handler(newvalue, oldvalue) {
        if (newvalue) {
          this.countDown()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    timeFormat(param) {
      // 处理数据永远是两位数
      return param < 10 ? '0' + param : param
    },
    countDown() {
      const that = this
      const newTime = new Date().getTime()
      const endTime = that.endTime
      if (endTime - newTime > 0) {
        const time = (endTime - newTime) / 1000
        const tempM = parseInt(((time % (60 * 60 * 24)) % 3600) / 60)
        const tempS = parseInt(((time % (60 * 60 * 24)) % 3600) % 60)
        that.model = {
          m: that.timeFormat(tempM),
          s: that.timeFormat(tempS)
        }
      } else {
        that.flag = false
        clearTimeout(that.timedown)
        that.timedown = null
        return false
      }
      this.timedown = setTimeout(this.countDown.bind(this), 1000)
    }
  }
}
</script>
